* s~\t+$~~
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 * @package MediaWiki
6 */
7
8 /**
9 *
10 */
11 require_once( 'WatchedItem.php' );
12
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
15
16 # Serialized record version
17 define( 'MW_USER_VERSION', 3 );
18
19 /**
20 *
21 * @package MediaWiki
22 */
23 class User {
24 /**#@+
25 * @access private
26 */
27 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
28 var $mEmailAuthenticated;
29 var $mRights, $mOptions;
30 var $mDataLoaded, $mNewpassword;
31 var $mSkin;
32 var $mBlockedby, $mBlockreason;
33 var $mTouched;
34 var $mToken;
35 var $mRealName;
36 var $mHash;
37 var $mGroups;
38 var $mVersion; // serialized version
39 var $mRegistration;
40
41 /** Construct using User:loadDefaults() */
42 function User() {
43 $this->loadDefaults();
44 $this->mVersion = MW_USER_VERSION;
45 }
46
47 /**
48 * Static factory method
49 * @param string $name Username, validated by Title:newFromText()
50 * @return User
51 * @static
52 */
53 function newFromName( $name ) {
54 # Force usernames to capital
55 global $wgContLang;
56 $name = $wgContLang->ucfirst( $name );
57
58 # Clean up name according to title rules
59 $t = Title::newFromText( $name );
60 if( is_null( $t ) ) {
61 return null;
62 }
63
64 # Reject various classes of invalid names
65 $canonicalName = $t->getText();
66 global $wgAuth;
67 $canonicalName = $wgAuth->getCanonicalName( $t->getText() );
68
69 if( !User::isValidUserName( $canonicalName ) ) {
70 return null;
71 }
72
73 $u = new User();
74 $u->setName( $canonicalName );
75 $u->setId( $u->idFromName( $canonicalName ) );
76 return $u;
77 }
78
79 /**
80 * Factory method to fetch whichever use has a given email confirmation code.
81 * This code is generated when an account is created or its e-mail address
82 * has changed.
83 *
84 * If the code is invalid or has expired, returns NULL.
85 *
86 * @param string $code
87 * @return User
88 * @static
89 */
90 function newFromConfirmationCode( $code ) {
91 $dbr =& wfGetDB( DB_SLAVE );
92 $name = $dbr->selectField( 'user', 'user_name', array(
93 'user_email_token' => md5( $code ),
94 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
95 ) );
96 if( is_string( $name ) ) {
97 return User::newFromName( $name );
98 } else {
99 return null;
100 }
101 }
102
103 /**
104 * Serialze sleep function, for better cache efficiency and avoidance of
105 * silly "incomplete type" errors when skins are cached
106 */
107 function __sleep() {
108 return array( 'mId', 'mName', 'mPassword', 'mEmail', 'mNewtalk',
109 'mEmailAuthenticated', 'mRights', 'mOptions', 'mDataLoaded',
110 'mNewpassword', 'mBlockedby', 'mBlockreason', 'mTouched',
111 'mToken', 'mRealName', 'mHash', 'mGroups', 'mRegistration' );
112 }
113
114 /**
115 * Get username given an id.
116 * @param integer $id Database user id
117 * @return string Nickname of a user
118 * @static
119 */
120 function whoIs( $id ) {
121 $dbr =& wfGetDB( DB_SLAVE );
122 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
123 }
124
125 /**
126 * Get real username given an id.
127 * @param integer $id Database user id
128 * @return string Realname of a user
129 * @static
130 */
131 function whoIsReal( $id ) {
132 $dbr =& wfGetDB( DB_SLAVE );
133 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
134 }
135
136 /**
137 * Get database id given a user name
138 * @param string $name Nickname of a user
139 * @return integer|null Database user id (null: if non existent
140 * @static
141 */
142 function idFromName( $name ) {
143 $fname = "User::idFromName";
144
145 $nt = Title::newFromText( $name );
146 if( is_null( $nt ) ) {
147 # Illegal name
148 return null;
149 }
150 $dbr =& wfGetDB( DB_SLAVE );
151 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
152
153 if ( $s === false ) {
154 return 0;
155 } else {
156 return $s->user_id;
157 }
158 }
159
160 /**
161 * does the string match an anonymous IPv4 address?
162 *
163 * Note: We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
164 * address because the usemod software would "cloak" anonymous IP
165 * addresses like this, if we allowed accounts like this to be created
166 * new users could get the old edits of these anonymous users.
167 *
168 * @bug 3631
169 *
170 * @static
171 * @param string $name Nickname of a user
172 * @return bool
173 */
174 function isIP( $name ) {
175 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/",$name);
176 /*return preg_match("/^
177 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
178 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
179 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
180 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
181 $/x", $name);*/
182 }
183
184 /**
185 * Is the input a valid username?
186 *
187 * Checks if the input is a valid username, we don't want an empty string,
188 * an IP address, anything that containins slashes (would mess up subpages),
189 * is longer than the maximum allowed username size or doesn't begin with
190 * a capital letter.
191 *
192 * @param string $name
193 * @return bool
194 * @static
195 */
196 function isValidUserName( $name ) {
197 global $wgContLang, $wgMaxNameChars;
198
199 if ( $name == ''
200 || User::isIP( $name )
201 || strpos( $name, '/' ) !== false
202 || strlen( $name ) > $wgMaxNameChars
203 || $name != $wgContLang->ucfirst( $name ) )
204 return false;
205
206 // Ensure that the name can't be misresolved as a different title,
207 // such as with extra namespace keys at the start.
208 $parsed = Title::newFromText( $name );
209 if( is_null( $parsed )
210 || $parsed->getNamespace()
211 || strcmp( $name, $parsed->getPrefixedText() ) )
212 return false;
213 else
214 return true;
215 }
216
217 /**
218 * Is the input a valid password?
219 *
220 * @param string $password
221 * @return bool
222 * @static
223 */
224 function isValidPassword( $password ) {
225 global $wgMinimalPasswordLength;
226 return strlen( $password ) >= $wgMinimalPasswordLength;
227 }
228
229 /**
230 * Does the string match roughly an email address ?
231 *
232 * There used to be a regular expression here, it got removed because it
233 * rejected valid addresses. Actually just check if there is '@' somewhere
234 * in the given address.
235 *
236 * @todo Check for RFC 2822 compilance
237 * @bug 959
238 *
239 * @param string $addr email address
240 * @static
241 * @return bool
242 */
243 function isValidEmailAddr ( $addr ) {
244 return ( trim( $addr ) != '' ) &&
245 (false !== strpos( $addr, '@' ) );
246 }
247
248 /**
249 * Count the number of edits of a user
250 *
251 * @param int $uid The user ID to check
252 * @return int
253 */
254 function edits( $uid ) {
255 $fname = 'User::edits';
256
257 $dbr =& wfGetDB( DB_SLAVE );
258 return $dbr->selectField(
259 'revision', 'count(*)',
260 array( 'rev_user' => $uid ),
261 $fname
262 );
263 }
264
265 /**
266 * probably return a random password
267 * @return string probably a random password
268 * @static
269 * @todo Check what is doing really [AV]
270 */
271 function randomPassword() {
272 global $wgMinimalPasswordLength;
273 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
274 $l = strlen( $pwchars ) - 1;
275
276 $pwlength = max( 7, $wgMinimalPasswordLength );
277 $digit = mt_rand(0, $pwlength - 1);
278 $np = '';
279 for ( $i = 0; $i < $pwlength; $i++ ) {
280 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
281 }
282 return $np;
283 }
284
285 /**
286 * Set properties to default
287 * Used at construction. It will load per language default settings only
288 * if we have an available language object.
289 */
290 function loadDefaults() {
291 static $n=0;
292 $n++;
293 $fname = 'User::loadDefaults' . $n;
294 wfProfileIn( $fname );
295
296 global $wgContLang, $wgDBname;
297 global $wgNamespacesToBeSearchedDefault;
298
299 $this->mId = 0;
300 $this->mNewtalk = -1;
301 $this->mName = false;
302 $this->mRealName = $this->mEmail = '';
303 $this->mEmailAuthenticated = null;
304 $this->mPassword = $this->mNewpassword = '';
305 $this->mRights = array();
306 $this->mGroups = array();
307 $this->mOptions = User::getDefaultOptions();
308
309 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
310 $this->mOptions['searchNs'.$nsnum] = $val;
311 }
312 unset( $this->mSkin );
313 $this->mDataLoaded = false;
314 $this->mBlockedby = -1; # Unset
315 $this->setToken(); # Random
316 $this->mHash = false;
317
318 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
319 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
320 }
321 else {
322 $this->mTouched = '0'; # Allow any pages to be cached
323 }
324
325 $this->mRegistration = wfTimestamp( TS_MW );
326
327 wfProfileOut( $fname );
328 }
329
330 /**
331 * Combine the language default options with any site-specific options
332 * and add the default language variants.
333 *
334 * @return array
335 * @static
336 * @access private
337 */
338 function getDefaultOptions() {
339 /**
340 * Site defaults will override the global/language defaults
341 */
342 global $wgContLang, $wgDefaultUserOptions;
343 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
344
345 /**
346 * default language setting
347 */
348 $variant = $wgContLang->getPreferredVariant();
349 $defOpt['variant'] = $variant;
350 $defOpt['language'] = $variant;
351
352 return $defOpt;
353 }
354
355 /**
356 * Get a given default option value.
357 *
358 * @param string $opt
359 * @return string
360 * @static
361 * @access public
362 */
363 function getDefaultOption( $opt ) {
364 $defOpts = User::getDefaultOptions();
365 if( isset( $defOpts[$opt] ) ) {
366 return $defOpts[$opt];
367 } else {
368 return '';
369 }
370 }
371
372 /**
373 * Get blocking information
374 * @access private
375 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
376 * non-critical checks are done against slaves. Check when actually saving should be done against
377 * master.
378 */
379 function getBlockedStatus( $bFromSlave = true ) {
380 global $wgEnableSorbs, $wgProxyWhitelist;
381
382 if ( -1 != $this->mBlockedby ) {
383 wfDebug( "User::getBlockedStatus: already loaded.\n" );
384 return;
385 }
386
387 $fname = 'User::getBlockedStatus';
388 wfProfileIn( $fname );
389 wfDebug( "$fname: checking...\n" );
390
391 $this->mBlockedby = 0;
392 $ip = wfGetIP();
393
394 # User/IP blocking
395 $block = new Block();
396 $block->fromMaster( !$bFromSlave );
397 if ( $block->load( $ip , $this->mId ) ) {
398 wfDebug( "$fname: Found block.\n" );
399 $this->mBlockedby = $block->mBy;
400 $this->mBlockreason = $block->mReason;
401 if ( $this->isLoggedIn() ) {
402 $this->spreadBlock();
403 }
404 } else {
405 wfDebug( "$fname: No block.\n" );
406 }
407
408 # Proxy blocking
409 if ( !$this->isSysop() && !in_array( $ip, $wgProxyWhitelist ) ) {
410
411 # Local list
412 if ( wfIsLocallyBlockedProxy( $ip ) ) {
413 $this->mBlockedby = wfMsg( 'proxyblocker' );
414 $this->mBlockreason = wfMsg( 'proxyblockreason' );
415 }
416
417 # DNSBL
418 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
419 if ( $this->inSorbsBlacklist( $ip ) ) {
420 $this->mBlockedby = wfMsg( 'sorbs' );
421 $this->mBlockreason = wfMsg( 'sorbsreason' );
422 }
423 }
424 }
425
426 # Extensions
427 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
428
429 wfProfileOut( $fname );
430 }
431
432 function inSorbsBlacklist( $ip ) {
433 global $wgEnableSorbs;
434 return $wgEnableSorbs &&
435 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
436 }
437
438 function inOpmBlacklist( $ip ) {
439 global $wgEnableOpm;
440 return $wgEnableOpm &&
441 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
442 }
443
444 function inDnsBlacklist( $ip, $base ) {
445 $fname = 'User::inDnsBlacklist';
446 wfProfileIn( $fname );
447
448 $found = false;
449 $host = '';
450
451 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
452 # Make hostname
453 for ( $i=4; $i>=1; $i-- ) {
454 $host .= $m[$i] . '.';
455 }
456 $host .= $base;
457
458 # Send query
459 $ipList = gethostbynamel( $host );
460
461 if ( $ipList ) {
462 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
463 $found = true;
464 } else {
465 wfDebug( "Requested $host, not found in $base.\n" );
466 }
467 }
468
469 wfProfileOut( $fname );
470 return $found;
471 }
472
473 /**
474 * Primitive rate limits: enforce maximum actions per time period
475 * to put a brake on flooding.
476 *
477 * Note: when using a shared cache like memcached, IP-address
478 * last-hit counters will be shared across wikis.
479 *
480 * @return bool true if a rate limiter was tripped
481 * @access public
482 */
483 function pingLimiter( $action='edit' ) {
484 global $wgRateLimits;
485 if( !isset( $wgRateLimits[$action] ) ) {
486 return false;
487 }
488 if( $this->isAllowed( 'delete' ) ) {
489 // goddam cabal
490 return false;
491 }
492
493 global $wgMemc, $wgDBname, $wgRateLimitLog;
494 $fname = 'User::pingLimiter';
495 wfProfileIn( $fname );
496
497 $limits = $wgRateLimits[$action];
498 $keys = array();
499 $id = $this->getId();
500 $ip = wfGetIP();
501
502 if( isset( $limits['anon'] ) && $id == 0 ) {
503 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
504 }
505
506 if( isset( $limits['user'] ) && $id != 0 ) {
507 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
508 }
509 if( $this->isNewbie() ) {
510 if( isset( $limits['newbie'] ) && $id != 0 ) {
511 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
512 }
513 if( isset( $limits['ip'] ) ) {
514 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
515 }
516 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
517 $subnet = $matches[1];
518 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
519 }
520 }
521
522 $triggered = false;
523 foreach( $keys as $key => $limit ) {
524 list( $max, $period ) = $limit;
525 $summary = "(limit $max in {$period}s)";
526 $count = $wgMemc->get( $key );
527 if( $count ) {
528 if( $count > $max ) {
529 wfDebug( "$fname: tripped! $key at $count $summary\n" );
530 if( $wgRateLimitLog ) {
531 @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
532 }
533 $triggered = true;
534 } else {
535 wfDebug( "$fname: ok. $key at $count $summary\n" );
536 }
537 } else {
538 wfDebug( "$fname: adding record for $key $summary\n" );
539 $wgMemc->add( $key, 1, intval( $period ) );
540 }
541 $wgMemc->incr( $key );
542 }
543
544 wfProfileOut( $fname );
545 return $triggered;
546 }
547
548 /**
549 * Check if user is blocked
550 * @return bool True if blocked, false otherwise
551 */
552 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
553 wfDebug( "User::isBlocked: enter\n" );
554 $this->getBlockedStatus( $bFromSlave );
555 return $this->mBlockedby !== 0;
556 }
557
558 /**
559 * Check if user is blocked from editing a particular article
560 */
561 function isBlockedFrom( $title, $bFromSlave = false ) {
562 global $wgBlockAllowsUTEdit;
563 $fname = 'User::isBlockedFrom';
564 wfProfileIn( $fname );
565 wfDebug( "$fname: enter\n" );
566
567 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
568 $title->getNamespace() == NS_USER_TALK )
569 {
570 $blocked = false;
571 wfDebug( "$fname: self-talk page, ignoring any blocks\n" );
572 } else {
573 wfDebug( "$fname: asking isBlocked()\n" );
574 $blocked = $this->isBlocked( $bFromSlave );
575 }
576 wfProfileOut( $fname );
577 return $blocked;
578 }
579
580 /**
581 * Get name of blocker
582 * @return string name of blocker
583 */
584 function blockedBy() {
585 $this->getBlockedStatus();
586 return $this->mBlockedby;
587 }
588
589 /**
590 * Get blocking reason
591 * @return string Blocking reason
592 */
593 function blockedFor() {
594 $this->getBlockedStatus();
595 return $this->mBlockreason;
596 }
597
598 /**
599 * Initialise php session
600 */
601 function SetupSession() {
602 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
603 if( $wgSessionsInMemcached ) {
604 require_once( 'MemcachedSessions.php' );
605 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
606 # If it's left on 'user' or another setting from another
607 # application, it will end up failing. Try to recover.
608 ini_set ( 'session.save_handler', 'files' );
609 }
610 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
611 session_cache_limiter( 'private, must-revalidate' );
612 @session_start();
613 }
614
615 /**
616 * Create a new user object using data from session
617 * @static
618 */
619 function loadFromSession() {
620 global $wgMemc, $wgDBname;
621
622 if ( isset( $_SESSION['wsUserID'] ) ) {
623 if ( 0 != $_SESSION['wsUserID'] ) {
624 $sId = $_SESSION['wsUserID'];
625 } else {
626 return new User();
627 }
628 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
629 $sId = intval( $_COOKIE["{$wgDBname}UserID"] );
630 $_SESSION['wsUserID'] = $sId;
631 } else {
632 return new User();
633 }
634 if ( isset( $_SESSION['wsUserName'] ) ) {
635 $sName = $_SESSION['wsUserName'];
636 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
637 $sName = $_COOKIE["{$wgDBname}UserName"];
638 $_SESSION['wsUserName'] = $sName;
639 } else {
640 return new User();
641 }
642
643 $passwordCorrect = FALSE;
644 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
645 if( !is_object( $user ) || $user->mVersion < MW_USER_VERSION ) {
646 # Expire old serialized objects; they may be corrupt.
647 $user = false;
648 }
649 if($makenew = !$user) {
650 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
651 $user = new User();
652 $user->mId = $sId;
653 $user->loadFromDatabase();
654 } else {
655 wfDebug( "User::loadFromSession() got from cache!\n" );
656 }
657
658 if ( isset( $_SESSION['wsToken'] ) ) {
659 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
660 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
661 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
662 } else {
663 return new User(); # Can't log in from session
664 }
665
666 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
667 if($makenew) {
668 if($wgMemc->set( $key, $user ))
669 wfDebug( "User::loadFromSession() successfully saved user\n" );
670 else
671 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
672 }
673 return $user;
674 }
675 return new User(); # Can't log in from session
676 }
677
678 /**
679 * Load a user from the database
680 */
681 function loadFromDatabase() {
682 $fname = "User::loadFromDatabase";
683
684 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
685 # loading in a command line script, don't assume all command line scripts need it like this
686 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
687 if ( $this->mDataLoaded ) {
688 return;
689 }
690
691 # Paranoia
692 $this->mId = intval( $this->mId );
693
694 /** Anonymous user */
695 if( !$this->mId ) {
696 /** Get rights */
697 $this->mRights = $this->getGroupPermissions( array( '*' ) );
698 $this->mDataLoaded = true;
699 return;
700 } # the following stuff is for non-anonymous users only
701
702 $dbr =& wfGetDB( DB_SLAVE );
703 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
704 'user_email_authenticated',
705 'user_real_name','user_options','user_touched', 'user_token', 'user_registration' ),
706 array( 'user_id' => $this->mId ), $fname );
707
708 if ( $s !== false ) {
709 $this->mName = $s->user_name;
710 $this->mEmail = $s->user_email;
711 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
712 $this->mRealName = $s->user_real_name;
713 $this->mPassword = $s->user_password;
714 $this->mNewpassword = $s->user_newpassword;
715 $this->decodeOptions( $s->user_options );
716 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
717 $this->mToken = $s->user_token;
718 $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
719
720 $res = $dbr->select( 'user_groups',
721 array( 'ug_group' ),
722 array( 'ug_user' => $this->mId ),
723 $fname );
724 $this->mGroups = array();
725 while( $row = $dbr->fetchObject( $res ) ) {
726 $this->mGroups[] = $row->ug_group;
727 }
728 $implicitGroups = array( '*', 'user' );
729
730 global $wgAutoConfirmAge;
731 $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
732 if( $accountAge >= $wgAutoConfirmAge ) {
733 $implicitGroups[] = 'autoconfirmed';
734 }
735
736 $effectiveGroups = array_merge( $implicitGroups, $this->mGroups );
737 $this->mRights = $this->getGroupPermissions( $effectiveGroups );
738 }
739
740 $this->mDataLoaded = true;
741 }
742
743 function getID() { return $this->mId; }
744 function setID( $v ) {
745 $this->mId = $v;
746 $this->mDataLoaded = false;
747 }
748
749 function getName() {
750 $this->loadFromDatabase();
751 if ( $this->mName === false ) {
752 $this->mName = wfGetIP();
753 }
754 return $this->mName;
755 }
756
757 function setName( $str ) {
758 $this->loadFromDatabase();
759 $this->mName = $str;
760 }
761
762
763 /**
764 * Return the title dbkey form of the name, for eg user pages.
765 * @return string
766 * @access public
767 */
768 function getTitleKey() {
769 return str_replace( ' ', '_', $this->getName() );
770 }
771
772 function getNewtalk() {
773 $this->loadFromDatabase();
774
775 # Load the newtalk status if it is unloaded (mNewtalk=-1)
776 if( $this->mNewtalk === -1 ) {
777 $this->mNewtalk = false; # reset talk page status
778
779 # Check memcached separately for anons, who have no
780 # entire User object stored in there.
781 if( !$this->mId ) {
782 global $wgDBname, $wgMemc;
783 $key = "$wgDBname:newtalk:ip:" . $this->getName();
784 $newtalk = $wgMemc->get( $key );
785 if( is_integer( $newtalk ) ) {
786 $this->mNewtalk = (bool)$newtalk;
787 } else {
788 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
789 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
790 }
791 } else {
792 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
793 }
794 }
795
796 return (bool)$this->mNewtalk;
797 }
798
799 /**
800 * Perform a user_newtalk check on current slaves; if the memcached data
801 * is funky we don't want newtalk state to get stuck on save, as that's
802 * damn annoying.
803 *
804 * @param string $field
805 * @param mixed $id
806 * @return bool
807 * @access private
808 */
809 function checkNewtalk( $field, $id ) {
810 $fname = 'User::checkNewtalk';
811 $dbr =& wfGetDB( DB_SLAVE );
812 $ok = $dbr->selectField( 'user_newtalk', $field,
813 array( $field => $id ), $fname );
814 return $ok !== false;
815 }
816
817 /**
818 * Add or update the
819 * @param string $field
820 * @param mixed $id
821 * @access private
822 */
823 function updateNewtalk( $field, $id ) {
824 $fname = 'User::updateNewtalk';
825 if( $this->checkNewtalk( $field, $id ) ) {
826 wfDebug( "$fname already set ($field, $id), ignoring\n" );
827 return false;
828 }
829 $dbw =& wfGetDB( DB_MASTER );
830 $dbw->insert( 'user_newtalk',
831 array( $field => $id ),
832 $fname,
833 'IGNORE' );
834 wfDebug( "$fname: set on ($field, $id)\n" );
835 return true;
836 }
837
838 /**
839 * Clear the new messages flag for the given user
840 * @param string $field
841 * @param mixed $id
842 * @access private
843 */
844 function deleteNewtalk( $field, $id ) {
845 $fname = 'User::deleteNewtalk';
846 if( !$this->checkNewtalk( $field, $id ) ) {
847 wfDebug( "$fname: already gone ($field, $id), ignoring\n" );
848 return false;
849 }
850 $dbw =& wfGetDB( DB_MASTER );
851 $dbw->delete( 'user_newtalk',
852 array( $field => $id ),
853 $fname );
854 wfDebug( "$fname: killed on ($field, $id)\n" );
855 return true;
856 }
857
858 /**
859 * Update the 'You have new messages!' status.
860 * @param bool $val
861 */
862 function setNewtalk( $val ) {
863 if( wfReadOnly() ) {
864 return;
865 }
866
867 $this->loadFromDatabase();
868 $this->mNewtalk = $val;
869
870 $fname = 'User::setNewtalk';
871
872 if( $this->isAnon() ) {
873 $field = 'user_ip';
874 $id = $this->getName();
875 } else {
876 $field = 'user_id';
877 $id = $this->getId();
878 }
879
880 if( $val ) {
881 $changed = $this->updateNewtalk( $field, $id );
882 } else {
883 $changed = $this->deleteNewtalk( $field, $id );
884 }
885
886 if( $changed ) {
887 if( $this->isAnon() ) {
888 // Anons have a separate memcached space, since
889 // user records aren't kept for them.
890 global $wgDBname, $wgMemc;
891 $key = "$wgDBname:newtalk:ip:$value";
892 $wgMemc->set( $key, $val ? 1 : 0 );
893 } else {
894 if( $val ) {
895 // Make sure the user page is watched, so a notification
896 // will be sent out if enabled.
897 $this->addWatch( $this->getTalkPage() );
898 }
899 }
900 $this->invalidateCache();
901 $this->saveSettings();
902 }
903 }
904
905 function invalidateCache() {
906 global $wgClockSkewFudge;
907 $this->loadFromDatabase();
908 $this->mTouched = wfTimestamp(TS_MW, time() + $wgClockSkewFudge );
909 # Don't forget to save the options after this or
910 # it won't take effect!
911 }
912
913 function validateCache( $timestamp ) {
914 $this->loadFromDatabase();
915 return ($timestamp >= $this->mTouched);
916 }
917
918 /**
919 * Encrypt a password.
920 * It can eventuall salt a password @see User::addSalt()
921 * @param string $p clear Password.
922 * @return string Encrypted password.
923 */
924 function encryptPassword( $p ) {
925 return wfEncryptPassword( $this->mId, $p );
926 }
927
928 # Set the password and reset the random token
929 function setPassword( $str ) {
930 $this->loadFromDatabase();
931 $this->setToken();
932 $this->mPassword = $this->encryptPassword( $str );
933 $this->mNewpassword = '';
934 }
935
936 # Set the random token (used for persistent authentication)
937 function setToken( $token = false ) {
938 global $wgSecretKey, $wgProxyKey, $wgDBname;
939 if ( !$token ) {
940 if ( $wgSecretKey ) {
941 $key = $wgSecretKey;
942 } elseif ( $wgProxyKey ) {
943 $key = $wgProxyKey;
944 } else {
945 $key = microtime();
946 }
947 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
948 } else {
949 $this->mToken = $token;
950 }
951 }
952
953
954 function setCookiePassword( $str ) {
955 $this->loadFromDatabase();
956 $this->mCookiePassword = md5( $str );
957 }
958
959 function setNewpassword( $str ) {
960 $this->loadFromDatabase();
961 $this->mNewpassword = $this->encryptPassword( $str );
962 }
963
964 function getEmail() {
965 $this->loadFromDatabase();
966 return $this->mEmail;
967 }
968
969 function getEmailAuthenticationTimestamp() {
970 $this->loadFromDatabase();
971 return $this->mEmailAuthenticated;
972 }
973
974 function setEmail( $str ) {
975 $this->loadFromDatabase();
976 $this->mEmail = $str;
977 }
978
979 function getRealName() {
980 $this->loadFromDatabase();
981 return $this->mRealName;
982 }
983
984 function setRealName( $str ) {
985 $this->loadFromDatabase();
986 $this->mRealName = $str;
987 }
988
989 function getOption( $oname ) {
990 $this->loadFromDatabase();
991 if ( array_key_exists( $oname, $this->mOptions ) ) {
992 return trim( $this->mOptions[$oname] );
993 } else {
994 return '';
995 }
996 }
997
998 function setOption( $oname, $val ) {
999 $this->loadFromDatabase();
1000 if ( $oname == 'skin' ) {
1001 # Clear cached skin, so the new one displays immediately in Special:Preferences
1002 unset( $this->mSkin );
1003 }
1004 $this->mOptions[$oname] = $val;
1005 $this->invalidateCache();
1006 }
1007
1008 function getRights() {
1009 $this->loadFromDatabase();
1010 return $this->mRights;
1011 }
1012
1013 /**
1014 * Get the list of explicit group memberships this user has.
1015 * The implicit * and user groups are not included.
1016 * @return array of strings
1017 */
1018 function getGroups() {
1019 $this->loadFromDatabase();
1020 return $this->mGroups;
1021 }
1022
1023 /**
1024 * Get the list of implicit group memberships this user has.
1025 * This includes all explicit groups, plus 'user' if logged in
1026 * and '*' for all accounts.
1027 * @return array of strings
1028 */
1029 function getEffectiveGroups() {
1030 $base = array( '*' );
1031 if( $this->isLoggedIn() ) {
1032 $base[] = 'user';
1033 }
1034 return array_merge( $base, $this->getGroups() );
1035 }
1036
1037 /**
1038 * Add the user to the given group.
1039 * This takes immediate effect.
1040 * @string $group
1041 */
1042 function addGroup( $group ) {
1043 $dbw =& wfGetDB( DB_MASTER );
1044 $dbw->insert( 'user_groups',
1045 array(
1046 'ug_user' => $this->getID(),
1047 'ug_group' => $group,
1048 ),
1049 'User::addGroup',
1050 array( 'IGNORE' ) );
1051
1052 $this->mGroups = array_merge( $this->mGroups, array( $group ) );
1053 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
1054
1055 $this->invalidateCache();
1056 $this->saveSettings();
1057 }
1058
1059 /**
1060 * Remove the user from the given group.
1061 * This takes immediate effect.
1062 * @string $group
1063 */
1064 function removeGroup( $group ) {
1065 $dbw =& wfGetDB( DB_MASTER );
1066 $dbw->delete( 'user_groups',
1067 array(
1068 'ug_user' => $this->getID(),
1069 'ug_group' => $group,
1070 ),
1071 'User::removeGroup' );
1072
1073 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1074 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
1075
1076 $this->invalidateCache();
1077 $this->saveSettings();
1078 }
1079
1080
1081 /**
1082 * A more legible check for non-anonymousness.
1083 * Returns true if the user is not an anonymous visitor.
1084 *
1085 * @return bool
1086 */
1087 function isLoggedIn() {
1088 return( $this->getID() != 0 );
1089 }
1090
1091 /**
1092 * A more legible check for anonymousness.
1093 * Returns true if the user is an anonymous visitor.
1094 *
1095 * @return bool
1096 */
1097 function isAnon() {
1098 return !$this->isLoggedIn();
1099 }
1100
1101 /**
1102 * Check if a user is sysop
1103 * @deprecated
1104 */
1105 function isSysop() {
1106 return $this->isAllowed( 'protect' );
1107 }
1108
1109 /** @deprecated */
1110 function isDeveloper() {
1111 return $this->isAllowed( 'siteadmin' );
1112 }
1113
1114 /** @deprecated */
1115 function isBureaucrat() {
1116 return $this->isAllowed( 'makesysop' );
1117 }
1118
1119 /**
1120 * Whether the user is a bot
1121 * @todo need to be migrated to the new user level management sytem
1122 */
1123 function isBot() {
1124 $this->loadFromDatabase();
1125 return in_array( 'bot', $this->mRights );
1126 }
1127
1128 /**
1129 * Check if user is allowed to access a feature / make an action
1130 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
1131 * @return boolean True: action is allowed, False: action should not be allowed
1132 */
1133 function isAllowed($action='') {
1134 if ( $action === '' )
1135 // In the spirit of DWIM
1136 return true;
1137
1138 $this->loadFromDatabase();
1139 return in_array( $action , $this->mRights );
1140 }
1141
1142 /**
1143 * Load a skin if it doesn't exist or return it
1144 * @todo FIXME : need to check the old failback system [AV]
1145 */
1146 function &getSkin() {
1147 global $IP, $wgRequest;
1148 if ( ! isset( $this->mSkin ) ) {
1149 $fname = 'User::getSkin';
1150 wfProfileIn( $fname );
1151
1152 # get the user skin
1153 $userSkin = $this->getOption( 'skin' );
1154 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1155
1156 $this->mSkin =& Skin::newFromKey( $userSkin );
1157 wfProfileOut( $fname );
1158 }
1159 return $this->mSkin;
1160 }
1161
1162 /**#@+
1163 * @param string $title Article title to look at
1164 */
1165
1166 /**
1167 * Check watched status of an article
1168 * @return bool True if article is watched
1169 */
1170 function isWatched( $title ) {
1171 $wl = WatchedItem::fromUserTitle( $this, $title );
1172 return $wl->isWatched();
1173 }
1174
1175 /**
1176 * Watch an article
1177 */
1178 function addWatch( $title ) {
1179 $wl = WatchedItem::fromUserTitle( $this, $title );
1180 $wl->addWatch();
1181 $this->invalidateCache();
1182 }
1183
1184 /**
1185 * Stop watching an article
1186 */
1187 function removeWatch( $title ) {
1188 $wl = WatchedItem::fromUserTitle( $this, $title );
1189 $wl->removeWatch();
1190 $this->invalidateCache();
1191 }
1192
1193 /**
1194 * Clear the user's notification timestamp for the given title.
1195 * If e-notif e-mails are on, they will receive notification mails on
1196 * the next change of the page if it's watched etc.
1197 */
1198 function clearNotification( &$title ) {
1199 global $wgUser, $wgUseEnotif;
1200
1201 if ($title->getNamespace() == NS_USER_TALK &&
1202 $title->getText() == $this->getName() ) {
1203 $this->setNewtalk( false );
1204 }
1205
1206 if( !$wgUseEnotif ) {
1207 return;
1208 }
1209
1210 if( $this->isAnon() ) {
1211 // Nothing else to do...
1212 return;
1213 }
1214
1215 // Only update the timestamp if the page is being watched.
1216 // The query to find out if it is watched is cached both in memcached and per-invocation,
1217 // and when it does have to be executed, it can be on a slave
1218 // If this is the user's newtalk page, we always update the timestamp
1219 if ($title->getNamespace() == NS_USER_TALK &&
1220 $title->getText() == $wgUser->getName())
1221 {
1222 $watched = true;
1223 } elseif ( $this->getID() == $wgUser->getID() ) {
1224 $watched = $title->userIsWatching();
1225 } else {
1226 $watched = true;
1227 }
1228
1229 // If the page is watched by the user (or may be watched), update the timestamp on any
1230 // any matching rows
1231 if ( $watched ) {
1232 $dbw =& wfGetDB( DB_MASTER );
1233 $success = $dbw->update( 'watchlist',
1234 array( /* SET */
1235 'wl_notificationtimestamp' => NULL
1236 ), array( /* WHERE */
1237 'wl_title' => $title->getDBkey(),
1238 'wl_namespace' => $title->getNamespace(),
1239 'wl_user' => $this->getID()
1240 ), 'User::clearLastVisited'
1241 );
1242 }
1243 }
1244
1245 /**#@-*/
1246
1247 /**
1248 * Resets all of the given user's page-change notification timestamps.
1249 * If e-notif e-mails are on, they will receive notification mails on
1250 * the next change of any watched page.
1251 *
1252 * @param int $currentUser user ID number
1253 * @access public
1254 */
1255 function clearAllNotifications( $currentUser ) {
1256 global $wgUseEnotif;
1257 if ( !$wgUseEnotif ) {
1258 $this->setNewtalk( false );
1259 return;
1260 }
1261 if( $currentUser != 0 ) {
1262
1263 $dbw =& wfGetDB( DB_MASTER );
1264 $success = $dbw->update( 'watchlist',
1265 array( /* SET */
1266 'wl_notificationtimestamp' => 0
1267 ), array( /* WHERE */
1268 'wl_user' => $currentUser
1269 ), 'UserMailer::clearAll'
1270 );
1271
1272 # we also need to clear here the "you have new message" notification for the own user_talk page
1273 # This is cleared one page view later in Article::viewUpdates();
1274 }
1275 }
1276
1277 /**
1278 * @access private
1279 * @return string Encoding options
1280 */
1281 function encodeOptions() {
1282 $a = array();
1283 foreach ( $this->mOptions as $oname => $oval ) {
1284 array_push( $a, $oname.'='.$oval );
1285 }
1286 $s = implode( "\n", $a );
1287 return $s;
1288 }
1289
1290 /**
1291 * @access private
1292 */
1293 function decodeOptions( $str ) {
1294 $a = explode( "\n", $str );
1295 foreach ( $a as $s ) {
1296 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1297 $this->mOptions[$m[1]] = $m[2];
1298 }
1299 }
1300 }
1301
1302 function setCookies() {
1303 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgDBname;
1304 if ( 0 == $this->mId ) return;
1305 $this->loadFromDatabase();
1306 $exp = time() + $wgCookieExpiration;
1307
1308 $_SESSION['wsUserID'] = $this->mId;
1309 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1310
1311 $_SESSION['wsUserName'] = $this->getName();
1312 setcookie( $wgDBname.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1313
1314 $_SESSION['wsToken'] = $this->mToken;
1315 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1316 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1317 } else {
1318 setcookie( $wgDBname.'Token', '', time() - 3600 );
1319 }
1320 }
1321
1322 /**
1323 * Logout user
1324 * It will clean the session cookie
1325 */
1326 function logout() {
1327 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgDBname;
1328 $this->loadDefaults();
1329 $this->setLoaded( true );
1330
1331 $_SESSION['wsUserID'] = 0;
1332
1333 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1334 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1335
1336 # Remember when user logged out, to prevent seeing cached pages
1337 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1338 }
1339
1340 /**
1341 * Save object settings into database
1342 */
1343 function saveSettings() {
1344 global $wgMemc, $wgDBname, $wgUseEnotif;
1345 $fname = 'User::saveSettings';
1346
1347 if ( wfReadOnly() ) { return; }
1348 if ( 0 == $this->mId ) { return; }
1349
1350 $dbw =& wfGetDB( DB_MASTER );
1351 $dbw->update( 'user',
1352 array( /* SET */
1353 'user_name' => $this->mName,
1354 'user_password' => $this->mPassword,
1355 'user_newpassword' => $this->mNewpassword,
1356 'user_real_name' => $this->mRealName,
1357 'user_email' => $this->mEmail,
1358 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1359 'user_options' => $this->encodeOptions(),
1360 'user_touched' => $dbw->timestamp($this->mTouched),
1361 'user_token' => $this->mToken
1362 ), array( /* WHERE */
1363 'user_id' => $this->mId
1364 ), $fname
1365 );
1366 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1367 }
1368
1369
1370 /**
1371 * Checks if a user with the given name exists, returns the ID
1372 */
1373 function idForName() {
1374 $fname = 'User::idForName';
1375
1376 $gotid = 0;
1377 $s = trim( $this->getName() );
1378 if ( 0 == strcmp( '', $s ) ) return 0;
1379
1380 $dbr =& wfGetDB( DB_SLAVE );
1381 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1382 if ( $id === false ) {
1383 $id = 0;
1384 }
1385 return $id;
1386 }
1387
1388 /**
1389 * Add user object to the database
1390 */
1391 function addToDatabase() {
1392 $fname = 'User::addToDatabase';
1393 $dbw =& wfGetDB( DB_MASTER );
1394 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1395 $dbw->insert( 'user',
1396 array(
1397 'user_id' => $seqVal,
1398 'user_name' => $this->mName,
1399 'user_password' => $this->mPassword,
1400 'user_newpassword' => $this->mNewpassword,
1401 'user_email' => $this->mEmail,
1402 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1403 'user_real_name' => $this->mRealName,
1404 'user_options' => $this->encodeOptions(),
1405 'user_token' => $this->mToken,
1406 'user_registration' => $dbw->timestamp( $this->mRegistration ),
1407 ), $fname
1408 );
1409 $this->mId = $dbw->insertId();
1410 }
1411
1412 function spreadBlock() {
1413 # If the (non-anonymous) user is blocked, this function will block any IP address
1414 # that they successfully log on from.
1415 $fname = 'User::spreadBlock';
1416
1417 wfDebug( "User:spreadBlock()\n" );
1418 if ( $this->mId == 0 ) {
1419 return;
1420 }
1421
1422 $userblock = Block::newFromDB( '', $this->mId );
1423 if ( !$userblock->isValid() ) {
1424 return;
1425 }
1426
1427 # Check if this IP address is already blocked
1428 $ipblock = Block::newFromDB( wfGetIP() );
1429 if ( $ipblock->isValid() ) {
1430 # If the user is already blocked. Then check if the autoblock would
1431 # excede the user block. If it would excede, then do nothing, else
1432 # prolong block time
1433 if ($userblock->mExpiry &&
1434 ($userblock->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
1435 return;
1436 }
1437 # Just update the timestamp
1438 $ipblock->updateTimestamp();
1439 return;
1440 }
1441
1442 # Make a new block object with the desired properties
1443 wfDebug( "Autoblocking {$this->mName}@" . wfGetIP() . "\n" );
1444 $ipblock->mAddress = wfGetIP();
1445 $ipblock->mUser = 0;
1446 $ipblock->mBy = $userblock->mBy;
1447 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1448 $ipblock->mTimestamp = wfTimestampNow();
1449 $ipblock->mAuto = 1;
1450 # If the user is already blocked with an expiry date, we don't
1451 # want to pile on top of that!
1452 if($userblock->mExpiry) {
1453 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1454 } else {
1455 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1456 }
1457
1458 # Insert it
1459 $ipblock->insert();
1460
1461 }
1462
1463 /**
1464 * Generate a string which will be different for any combination of
1465 * user options which would produce different parser output.
1466 * This will be used as part of the hash key for the parser cache,
1467 * so users will the same options can share the same cached data
1468 * safely.
1469 *
1470 * Extensions which require it should install 'PageRenderingHash' hook,
1471 * which will give them a chance to modify this key based on their own
1472 * settings.
1473 *
1474 * @return string
1475 */
1476 function getPageRenderingHash() {
1477 global $wgContLang;
1478 if( $this->mHash ){
1479 return $this->mHash;
1480 }
1481
1482 // stubthreshold is only included below for completeness,
1483 // it will always be 0 when this function is called by parsercache.
1484
1485 $confstr = $this->getOption( 'math' );
1486 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1487 $confstr .= '!' . $this->getOption( 'date' );
1488 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
1489 $confstr .= '!' . $this->getOption( 'language' );
1490 $confstr .= '!' . $this->getOption( 'thumbsize' );
1491 // add in language specific options, if any
1492 $extra = $wgContLang->getExtraHashOptions();
1493 $confstr .= $extra;
1494
1495 // Give a chance for extensions to modify the hash, if they have
1496 // extra options or other effects on the parser cache.
1497 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
1498
1499 $this->mHash = $confstr;
1500 return $confstr;
1501 }
1502
1503 function isAllowedToCreateAccount() {
1504 return $this->isAllowed( 'createaccount' ) && !$this->isBlocked();
1505 }
1506
1507 /**
1508 * Set mDataLoaded, return previous value
1509 * Use this to prevent DB access in command-line scripts or similar situations
1510 */
1511 function setLoaded( $loaded ) {
1512 return wfSetVar( $this->mDataLoaded, $loaded );
1513 }
1514
1515 /**
1516 * Get this user's personal page title.
1517 *
1518 * @return Title
1519 * @access public
1520 */
1521 function getUserPage() {
1522 return Title::makeTitle( NS_USER, $this->getName() );
1523 }
1524
1525 /**
1526 * Get this user's talk page title.
1527 *
1528 * @return Title
1529 * @access public
1530 */
1531 function getTalkPage() {
1532 $title = $this->getUserPage();
1533 return $title->getTalkPage();
1534 }
1535
1536 /**
1537 * @static
1538 */
1539 function getMaxID() {
1540 static $res; // cache
1541
1542 if ( isset( $res ) )
1543 return $res;
1544 else {
1545 $dbr =& wfGetDB( DB_SLAVE );
1546 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
1547 }
1548 }
1549
1550 /**
1551 * Determine whether the user is a newbie. Newbies are either
1552 * anonymous IPs, or the most recently created accounts.
1553 * @return bool True if it is a newbie.
1554 */
1555 function isNewbie() {
1556 return !$this->isAllowed( 'autoconfirmed' );
1557 }
1558
1559 /**
1560 * Check to see if the given clear-text password is one of the accepted passwords
1561 * @param string $password User password.
1562 * @return bool True if the given password is correct otherwise False.
1563 */
1564 function checkPassword( $password ) {
1565 global $wgAuth, $wgMinimalPasswordLength;
1566 $this->loadFromDatabase();
1567
1568 // Even though we stop people from creating passwords that
1569 // are shorter than this, doesn't mean people wont be able
1570 // to. Certain authentication plugins do NOT want to save
1571 // domain passwords in a mysql database, so we should
1572 // check this (incase $wgAuth->strict() is false).
1573 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1574 return false;
1575 }
1576
1577 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1578 return true;
1579 } elseif( $wgAuth->strict() ) {
1580 /* Auth plugin doesn't allow local authentication */
1581 return false;
1582 }
1583 $ep = $this->encryptPassword( $password );
1584 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1585 return true;
1586 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1587 return true;
1588 } elseif ( function_exists( 'iconv' ) ) {
1589 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1590 # Check for this with iconv
1591 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1592 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1593 return true;
1594 }
1595 }
1596 return false;
1597 }
1598
1599 /**
1600 * Initialize (if necessary) and return a session token value
1601 * which can be used in edit forms to show that the user's
1602 * login credentials aren't being hijacked with a foreign form
1603 * submission.
1604 *
1605 * @param mixed $salt - Optional function-specific data for hash.
1606 * Use a string or an array of strings.
1607 * @return string
1608 * @access public
1609 */
1610 function editToken( $salt = '' ) {
1611 if( !isset( $_SESSION['wsEditToken'] ) ) {
1612 $token = $this->generateToken();
1613 $_SESSION['wsEditToken'] = $token;
1614 } else {
1615 $token = $_SESSION['wsEditToken'];
1616 }
1617 if( is_array( $salt ) ) {
1618 $salt = implode( '|', $salt );
1619 }
1620 return md5( $token . $salt );
1621 }
1622
1623 /**
1624 * Generate a hex-y looking random token for various uses.
1625 * Could be made more cryptographically sure if someone cares.
1626 * @return string
1627 */
1628 function generateToken( $salt = '' ) {
1629 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1630 return md5( $token . $salt );
1631 }
1632
1633 /**
1634 * Check given value against the token value stored in the session.
1635 * A match should confirm that the form was submitted from the
1636 * user's own login session, not a form submission from a third-party
1637 * site.
1638 *
1639 * @param string $val - the input value to compare
1640 * @param string $salt - Optional function-specific data for hash
1641 * @return bool
1642 * @access public
1643 */
1644 function matchEditToken( $val, $salt = '' ) {
1645 global $wgMemc;
1646
1647 /*
1648 if ( !isset( $_SESSION['wsEditToken'] ) ) {
1649 $logfile = '/home/wikipedia/logs/session_debug/session.log';
1650 $mckey = memsess_key( session_id() );
1651 $uname = @posix_uname();
1652 $msg = "wsEditToken not set!\n" .
1653 'apache server=' . $uname['nodename'] . "\n" .
1654 'session_id = ' . session_id() . "\n" .
1655 '$_SESSION=' . var_export( $_SESSION, true ) . "\n" .
1656 '$_COOKIE=' . var_export( $_COOKIE, true ) . "\n" .
1657 "mc get($mckey) = " . var_export( $wgMemc->get( $mckey ), true ) . "\n\n\n";
1658
1659 @error_log( $msg, 3, $logfile );
1660 }
1661 */
1662 return ( $val == $this->editToken( $salt ) );
1663 }
1664
1665 /**
1666 * Generate a new e-mail confirmation token and send a confirmation
1667 * mail to the user's given address.
1668 *
1669 * @return mixed True on success, a WikiError object on failure.
1670 */
1671 function sendConfirmationMail() {
1672 global $wgContLang;
1673 $url = $this->confirmationTokenUrl( $expiration );
1674 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1675 wfMsg( 'confirmemail_body',
1676 wfGetIP(),
1677 $this->getName(),
1678 $url,
1679 $wgContLang->timeanddate( $expiration, false ) ) );
1680 }
1681
1682 /**
1683 * Send an e-mail to this user's account. Does not check for
1684 * confirmed status or validity.
1685 *
1686 * @param string $subject
1687 * @param string $body
1688 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1689 * @return mixed True on success, a WikiError object on failure.
1690 */
1691 function sendMail( $subject, $body, $from = null ) {
1692 if( is_null( $from ) ) {
1693 global $wgPasswordSender;
1694 $from = $wgPasswordSender;
1695 }
1696
1697 require_once( 'UserMailer.php' );
1698 $to = new MailAddress( $this );
1699 $sender = new MailAddress( $from );
1700 $error = userMailer( $to, $sender, $subject, $body );
1701
1702 if( $error == '' ) {
1703 return true;
1704 } else {
1705 return new WikiError( $error );
1706 }
1707 }
1708
1709 /**
1710 * Generate, store, and return a new e-mail confirmation code.
1711 * A hash (unsalted since it's used as a key) is stored.
1712 * @param &$expiration mixed output: accepts the expiration time
1713 * @return string
1714 * @access private
1715 */
1716 function confirmationToken( &$expiration ) {
1717 $fname = 'User::confirmationToken';
1718
1719 $now = time();
1720 $expires = $now + 7 * 24 * 60 * 60;
1721 $expiration = wfTimestamp( TS_MW, $expires );
1722
1723 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1724 $hash = md5( $token );
1725
1726 $dbw =& wfGetDB( DB_MASTER );
1727 $dbw->update( 'user',
1728 array( 'user_email_token' => $hash,
1729 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1730 array( 'user_id' => $this->mId ),
1731 $fname );
1732
1733 return $token;
1734 }
1735
1736 /**
1737 * Generate and store a new e-mail confirmation token, and return
1738 * the URL the user can use to confirm.
1739 * @param &$expiration mixed output: accepts the expiration time
1740 * @return string
1741 * @access private
1742 */
1743 function confirmationTokenUrl( &$expiration ) {
1744 $token = $this->confirmationToken( $expiration );
1745 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1746 return $title->getFullUrl();
1747 }
1748
1749 /**
1750 * Mark the e-mail address confirmed and save.
1751 */
1752 function confirmEmail() {
1753 $this->loadFromDatabase();
1754 $this->mEmailAuthenticated = wfTimestampNow();
1755 $this->saveSettings();
1756 return true;
1757 }
1758
1759 /**
1760 * Is this user allowed to send e-mails within limits of current
1761 * site configuration?
1762 * @return bool
1763 */
1764 function canSendEmail() {
1765 return $this->isEmailConfirmed();
1766 }
1767
1768 /**
1769 * Is this user allowed to receive e-mails within limits of current
1770 * site configuration?
1771 * @return bool
1772 */
1773 function canReceiveEmail() {
1774 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1775 }
1776
1777 /**
1778 * Is this user's e-mail address valid-looking and confirmed within
1779 * limits of the current site configuration?
1780 *
1781 * If $wgEmailAuthentication is on, this may require the user to have
1782 * confirmed their address by returning a code or using a password
1783 * sent to the address from the wiki.
1784 *
1785 * @return bool
1786 */
1787 function isEmailConfirmed() {
1788 global $wgEmailAuthentication;
1789 $this->loadFromDatabase();
1790 if( $this->isAnon() )
1791 return false;
1792 if( !$this->isValidEmailAddr( $this->mEmail ) )
1793 return false;
1794 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1795 return false;
1796 return true;
1797 }
1798
1799 /**
1800 * @param array $groups list of groups
1801 * @return array list of permission key names for given groups combined
1802 * @static
1803 */
1804 function getGroupPermissions( $groups ) {
1805 global $wgGroupPermissions;
1806 $rights = array();
1807 foreach( $groups as $group ) {
1808 if( isset( $wgGroupPermissions[$group] ) ) {
1809 $rights = array_merge( $rights,
1810 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
1811 }
1812 }
1813 return $rights;
1814 }
1815
1816 /**
1817 * @param string $group key name
1818 * @return string localized descriptive name, if provided
1819 * @static
1820 */
1821 function getGroupName( $group ) {
1822 $key = "group-$group-name";
1823 $name = wfMsg( $key );
1824 if( $name == '' || $name == "&lt;$key&gt;" ) {
1825 return $group;
1826 } else {
1827 return $name;
1828 }
1829 }
1830
1831 /**
1832 * Return the set of defined explicit groups.
1833 * The * and 'user' groups are not included.
1834 * @return array
1835 * @static
1836 */
1837 function getAllGroups() {
1838 global $wgGroupPermissions;
1839 return array_diff(
1840 array_keys( $wgGroupPermissions ),
1841 array( '*', 'user', 'autoconfirmed' ) );
1842 }
1843
1844 }
1845
1846 ?>